<template>
  <div :class="itemLayoutClass">
    <div :class="itemLayoutClass + '-head-input'">
      <a-input placeholder="搜索" @change="onSearch" allow-clear>
        <a-icon
          slot="prefix"
          type="search"
          :style="{
            color: '#999b9e',
          }"
        />
      </a-input>
    </div>
    <a-spin :spinning="isLoading || confirmLoading">
      <div :class="itemLayoutClass + '-content'" ref="pullcontent">
        <pull-to
          @infinite-scroll="scrollArivedBottom"
          @scroll="screenScroll"
          ref="pullto"
        >
          <template>
            <wdsq :jsonList="items" :itemNow="itemNow" @btn-click="itemClick" />
          </template>

          <template v-if="items.length === 0 && !(isLoading || confirmLoading)">
            <div :class="itemLayoutClass + '-empty'">
              <img src="~@/assets/img/empty.png" />
            </div>
          </template>
          <div
            :class="fixedEndLine ? 'is-to-bottom-fixed' : 'is-to-bottom-normal'"
            v-show="toEnd && items && items.length"
            ref="endline"
          >
            <a-divider><span>我可是有底线的</span></a-divider>
          </div>
        </pull-to>
        <a-back-top />
      </div>
    </a-spin>
  </div>
</template>

<script type="text/ecmascript-6">
/* eslint-disabled */
import {
 myApplyTaskList,
        myApproveList,
        getInstanceOpinion,
        bpmTodoTaskList,
        getSidByDefKey,
        getKeyByMenuId,
        receiveList,
        updateRead,
        getAllProcess,
        taskCheck
   } from '@/api/itemLayout';
import PullTo from 'vue-pull-to';
import { id } from '@/views/home/jsondata';
import Wdsq from './itemlayout/itemlayout-wdsq/index.vue';
import {debounce, initNavTitle} from '@/utils/utils.ts'
import ddGoBackFilter from "@/views/home/homemixin";

export default {
    data() {
        return {
            [id]:'',
            confirmLoading:false,
            fixedEndLine:false,
            toEnd:false,
            isLoading:false,
            itemLayoutClass: 'itemLayout',
            itemNow: '',
            items: [],
            limit: 40, // pageSize
            pageIndex: 1,
            isNextPage: true,
            endlineHeight:0,
            clientHeight:0
        };
    },
    mixins:[ddGoBackFilter],
    methods: {
        getAllProcess(search = '', type){
            const pageBrfore = this.pageIndex;
            if (type === 'loadmore') {
                this.pageIndex += 1;
            }
            this.isLoading = true
            const obj = {"subject":search,"pageSize":this.limit,"pageIndex":this.pageIndex}
            getAllProcess(obj).then(res => {
                this.isLoading = false
                if (res.code === 10020) {
                     this.toEnd = true
                 }
                if (res.code === 200 && res.success) {
                    if (res.data.length < this.limit) {
                        this.toEnd = true
                    }
                    res.data.forEach((item) => {
                        // eslint-disable-next-line no-param-reassign
                        item[id] = '1-3';
                    });
                    // this.items = res.data;
                       if (search) {
                            this.items = res.data;
                        } else {
                            this.items = this.items.concat(res.data);
                        }
                } else if(type === 'loadmore') {
                        this.pageIndex = pageBrfore;
                    }
            })
        },
        screenScroll(e){
             const e1 = document.querySelector('.a-inline-message')
              const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                 if ( e1 && (e1.scrollHeight < clientHeight - 30)) {
                this.fixedEndLine = true
            }else{
                this.fixedEndLine = false
            }
        },
        onSearch(search) {
            this.items = [];
            this.pageIndex = 1;
            this.toEnd = false;
            return this.getRightRequest(search.target._value);
        },
         loadMore() {
             if (this.toEnd) {
                 return
             }
            return this.getRightRequest(undefined, 'loadmore');
        },
        scrollArivedBottom() {
            return this.loadMore();
        },
        async addLiuChengToRes(res, search = '') {
            for (let i = 0; i < res.data.length; i += 1) {
                res.data[i][id] = '1-0';
                // eslint-disable-next-line no-await-in-loop
               /*  await getInstanceOpinion({ instId: res.data[i].instId }).then((res1) => {
                    if (res1.code === 200 && res1.success) {
                        const regex = /[^-]+(?=-)/g;
                        if (res1.data) {
                            if (res1.data.length) {
                                const liuc = res1.data[res1.data.length - 1];
                                const arr = liuc.assignInfo.split(',');
                                const brr = [];
                                arr.pop();
                                arr.forEach((item) => {
                                    brr.push(item.match(regex)[1]);
                                });
                                // eslint-disable-next-line no-param-reassign
                                res1.data[res1.data.length - 1].assignInfo = brr.toString();
                            }
                        }
                        res.data[i].liucheng = res1.data;
                    }
                }); */
                res.data[i].assignInfo = this.filterAssignInfo(res.data[i].assigneeNames)
            }
            if (search) {
                this.items = res.data;
            } else {
                this.items = this.items.concat(res.data);
            }
        },
        filterAssignInfo(str){
            if (!str) {
                return
            }
            const arr = str.split(',');
                const brr = [];
                if (arr) {
                    arr.forEach(item=>{
                        item = item.replace(/\[用户\]/g,'').replace(/;/g,',')
                        brr.push(item)
                    })
                }
                return brr.length ? brr.toString() : ''
        },
        // 抄送
        receiveList(search = '', type){
            const pageBrfore = this.pageIndex;
            if (type === 'loadmore') {
                this.pageIndex += 1;
            }

            const obj = {
                order: 'asc',
                offset: (this.pageIndex - 1) * this.limit,
                limit: this.limit,
                'task.subject_^VLK': search,
                };
                if (search) {
                    obj.limit = 100
                }
                if (this.toEnd) {
                    return
                }
                this.isLoading = true
            receiveList(obj).then((res) => {
                this[id] = '1-2'
                this.isLoading = false
                if (res.code === 10020) {
                     this.toEnd = true
                 }
                if (res.code === 200 && res.success) {
                    if (res.data.length < this.limit) {
                        this.toEnd = true
                    }
                    res.data.forEach((item) => {
                        item[id] = '1-2';
                    });
                    // this.items = res.data;
                       if (search) {
                            this.items = res.data;
                        } else {
                            this.items = this.items.concat(res.data);
                        }
                } else if(type === 'loadmore') {
                        this.pageIndex = pageBrfore;
                    }
            },err=>{
                this.isLoading = false
                this.$message.error('服务器繁忙')
            });
        },
        // 我的申请  1-0
         myApplyTaskList(search = '', type) {
            const pageBrfore = this.pageIndex;
            if (type === 'loadmore') {
                this.pageIndex += 1;
            }

            const obj = {
                order: 'asc',
                offset: (this.pageIndex - 1) * this.limit,
                limit: this.limit,
                // "task.subject_^VLK": search
                'task.subject_^VLK': search,
                };
                if (search) {
                    obj.limit = 100
                }
                if (this.toEnd) {
                    return
                }
                 this.isLoading = true
             myApplyTaskList(obj).then((res) => {
                 this.isLoading = false
                 if (res.code === 10020) {
                     this.toEnd = true
                 }
                if (res.code === 200 && res.success) {
                    if (res.data.length < this.limit) {
                        this.toEnd = true
                    }
                    this.addLiuChengToRes(res, search);
                } else if (type === 'loadmore') {
                        this.pageIndex = pageBrfore;
                    }
            },err=>{
                this.isLoading = false
                this.$message.error('服务器繁忙')
            });
        },
        // 已办申请
        myApproveList(search = '', type) {

            const pageBrfore = this.pageIndex;
            if (type === 'loadmore') {
                this.pageIndex += 1;
            }

            const obj = {
                order: 'asc',
                offset: (this.pageIndex - 1) * this.limit,
                limit: this.limit,
                'task.subject_^VLK': search,
                };
                if (search) {
                    obj.limit = 100
                }
                if (this.toEnd) {
                    return
                }
                this.isLoading = true
            myApproveList(obj).then((res) => {
                this.isLoading = false
                if (res.code === 10020) {
                     this.toEnd = true
                 }
                if (res.code === 200 && res.success) {
                    if (res.data.length < this.limit) {
                        this.toEnd = true
                    }
                    res.data.forEach((item) => {
                        item[id] = '1-3';
                    });
                    // this.items = res.data;
                       if (search) {
                            this.items = res.data;
                        } else {

                            this.items = this.items.concat(res.data);
                        }
                } else if(type === 'loadmore') {
                        this.pageIndex = pageBrfore;
                    }
            },err => {
                this.isLoading = false
                this.$message.error('服务器繁忙')
            });
        },
        // 待办申请

        bpmTodoTaskList(search = '', type) {
            const pageBrfore = this.pageIndex;
            if (type === 'loadmore') {
                this.pageIndex += 1;
            }

            const obj = {
                order: 'asc',
                offset: (this.pageIndex - 1) * this.limit,
                limit: this.limit,
                'task.subject_^VLK': search,
                'task.type_id_^VEQ': this.itemNow,
                };
                if (search) {
                    obj.limit = 100
                }
                if (this.toEnd) {
                    return
                }
                this.isLoading = true
            bpmTodoTaskList(obj).then((res) => {
                if (res.code === 10020) {
                     this.toEnd = true
                 }
                this.isLoading = false
                if (res.code === 200 && res.success) {
                    if (res.data.length < this.limit) {
                        this.toEnd = true
                    }

                    if (search) {
                        this.items = res.data;
                    }else{
                        this.items = this.items.concat(res.data)
                    }
                } else if(type === 'loadmore') {
                        this.pageIndex = pageBrfore;
                    }
            },err=>{
                this.isLoading = false
                this.$message.error('服务器繁忙')
            });
        },

        async getSidByDefKey(data){
            let obj = {}
           await getSidByDefKey(data).then(res=>{

                if (res.code === 200 && res.success) {
                    if (res.data.sId) {
                        obj.sid = res.data.sId
                        obj.responseUrl1 = res.data.responseUrl
                        obj.tableId1 = res.data.tableId || res.data.budgetTableId
                        obj.fileType1 = res.data.fileType
                        sessionStorage.setItem('matterSxuuid',res.data.matterSxuuid || '')
                    }
                }else{
                    this.$message.error(res.message)
                }
            })
            return new Promise((resolve)=> resolve(obj))
        },
        async getKeyByMenuId(data){
            let data1
            await getKeyByMenuId(data).then(res=>{
                if (res.code === 200 && res.success) {
                    data1 = res.data
                }
            })
            return new Promise((resolve)=> resolve(data1 || false))
        },
        async itemClick(item){
            if (this.itemNow !== '1-2'){
                this.confirmLoading = true
                // const checkRes = await taskCheck({taskId:item.taskId})
                // console.log(checkRes);
            }else{
                //更新状态
                await updateRead({
                    id: item.id
                })
            }

            let enterpriseId, sId, id, key, formGuid, responseUrl, tableId, fileType
            enterpriseId = localStorage.getItem('enterpriseId')
            const obj = {
                key: item.defKey
            }
            await this.getSidByDefKey(obj).then(({sid,responseUrl1,tableId1,fileType1})=>{
                sId = sid
                fileType = fileType1
                responseUrl = responseUrl1
                tableId = tableId1
            })

            this.confirmLoading = false
            // await this.getKeyByMenuId({menuId: '1598598807063'}).then(res=>{
            //     if (res) {
            //         sId = res.sId
            //         id = res.id
            //         key = res.key
            //     }
            // })
            if (sId) {
                const showSPBtns = sessionStorage.getItem('showSPBtns');
                let params = 'a'
                console.log(item);
                params += `&title=${item.subject}&sid=${sId}`
                params += `&enterpriseId=${enterpriseId}`
                params += `&enterpriseName=${item.enterpriseName}`
                params += `&assigneeNames=${item.assigneeNames}`
                params += `&instId=${item.instId}`
                params += `&taskId=${item.taskId}`
                params += `&nodeId=${item.nodeId}`
                params += `&defId=${item.defId}`
                params += `&formName=${item.formName}`
                params += `&responseUrl=${responseUrl}`
                params += `&tableId=${tableId}`
                params += `&showSPBtns=${showSPBtns}`
                params += `&fileType=${fileType}`
                if (item.bizKey) {
                    formGuid = item.bizKey
                }
                params += `&formGuid=${formGuid}`
                this.$router.push(`/detailPage?${params}`)
            }
        },

    },
    computed: {
        getRightRequest() {
            const type = this.itemNow;
            if (type === '1-0') {
                return this.myApplyTaskList;
            }
            if (type === '1-1') {
                return this.myApproveList;
            }
            if (type === '1-2') {
                return this.receiveList;
            }
            if (type === '1-3') {
                return this.getAllProcess;
            }
            return this.bpmTodoTaskList;
        },
    },

    created() {
        const backItemLayout = localStorage.getItem('backItemLayout')
        if (backItemLayout === '1') {
            localStorage.setItem('backItemLayout','')
            window.location.reload()
        }
        localStorage.setItem('sid','')
        const itemNow = sessionStorage.getItem('homeItemClick');
        this.onSearch = debounce(this.onSearch,500)
        if (itemNow) {
            this.itemNow = itemNow;
        } else {
            this.$router.push('/');
        }
        const flowLayoutName = sessionStorage.getItem('flowLayoutName')
        flowLayoutName && initNavTitle(flowLayoutName)
    },
    components: {
        PullTo,
        Wdsq,
    },

    mounted() {
         this.getRightRequest();
    },
    watch:{
        'items':{
            handler:function() {
                setTimeout(() => {
                    this.screenScroll()
                    // const ele =this.$refs.pullto
                    // console.log(ele.$el.scrollTop);
                    // ele ?  ele.scrollTo() : ''


                });
            }
        }
    }
};
</script>
